package com.deyun.charpt01.async

import com.deyun.charpt01.common.HttpError
import com.deyun.charpt01.common.HttpException
import com.deyun.charpt01.common.HttpService
import kotlin.coroutines.experimental.*

fun 我要开始协程了(context: CoroutineContext = EmptyCoroutineContext, block: suspend () -> Unit) {
    block.startCoroutine(ContextContinuation(context + AsyncContext()))
}

suspend fun <T> 我要进行耗时操作(block: CoroutineContext.() -> T) = suspendCoroutine<T> { continuation ->
    AsyncTask {
        try {
            continuation.resume(block(continuation.context))
        } catch (e: Exception) {
            continuation.resumeWithException(e)
        }
    }.execute()
}

fun 我要开始加载图片(url: String): ByteArray {
        val responseBody = HttpService.service.getLogo(url).execute()
        if (responseBody.isSuccessful) {
            responseBody.body()?.byteStream()?.readBytes()?.let {
                return it
            }
            throw HttpException(HttpError.HTTP_ERROR_NO_DATA)
        } else {
            throw HttpException(responseBody.code())
        }
}